<template>
  <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false">
    <CommentItem v-for="(item, index) in list" :key="index" :error="error" error-text="加载失败，稍后重试！" :comment="item" @reply-click="$emit('reply-click', $event)" />
  </van-list>
</template>

<script>
import { getCommentAPI } from '@/api/Comment.js'
import CommentItem from './comment-item.vue'
export default {
  name: 'commontList',
  props: {
    scurce: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator(value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 10,
      error: false
    }
  },
  created() {
    this.loading = true
    this.onLoad()
  },
  methods: {
    async onLoad() {
      try {
        // 1.请求获取数据
        const { data } = await getCommentAPI({
          type: this.type, //评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.scurce.toString(), //源id，文章id或评论id
          offset: this.offset, //获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
          limit: this.limit
        })
        console.log(data)
        // 2.将数据添加到列表中
        const { results } = data.data
        this.$emit('onload-success', data.data)
        this.list.push(...results)
        // 3，将loading设置为false
        this.loading = false
        // 4判断是否还有数据
        if (results.length) {
          // 有就更新获取下一页数据页码
          this.offset = data.data.end_id
        }
        this.finished = true
        // 没有就将finished设置为结束
      } catch (err) {
        // console.log(err)
        this.error = true
        this.loading = true
      }
    }
  },
  components: {
    CommentItem
  }
}
</script>

<style lang="less" scoped></style>
